package dto

import (
	"io"
	"oss-api/boot"
	"oss-api/library/storage"
)

const (
	AliYun   = "ali_yun"
	Location = "location"
)

// IStorage 数据源相关操作接口
type IStorage interface {
	CreateFolder(name string) (bool, error) // 创建文件夹
	UploadFile(name string, reader io.Reader) (string, error)
	DeleteResource(path ...string) error           // 删除元素
	SetResourcePerm(path string, state bool) error // 设置访问权限
}

var Storage = NewOperator()

// Operator 具体相关操作
type Operator struct {
	strategy IStorage
}

func NewOperator() *Operator {
	var s IStorage
	switch boot.Config.Storage.Default {
	case AliYun:
		s = storage.NewAliYunStorage()
	case Location:
		s = storage.NewLocationStorage()
	default:
		s = nil
	}
	return &Operator{
		strategy: s,
	}
}

func (o *Operator) before() {
	if o.strategy == nil {
		var s IStorage
		switch boot.Config.Storage.Default {
		case AliYun:
			s = storage.NewAliYunStorage()
		case Location:
			s = storage.NewLocationStorage()
		default:
			s = nil
		}
		o.strategy = s
	}
}

func (o *Operator) CreateCategory(name string) (bool, error) {
	o.before()
	return o.strategy.CreateFolder(name)
}

func (o *Operator) UploadFile(name string, reader io.Reader) (string, error) {

	var (
		url string
		err error
	)
	o.before()
	if url, err = o.strategy.UploadFile(name, reader); err != nil {
		return "", err
	}
	return url, nil
}

func (o *Operator) DeleteResource(obj ...string) error {
	o.before()
	return o.strategy.DeleteResource(obj...)
}

func (o *Operator) SetResourcePerm(path string, state bool) error {
	o.before()
	return o.strategy.SetResourcePerm(path, state)
}
